package com.apes.scm.masterdata.product.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.product.model.ServeType;
import com.apes.scm.masterdata.product.repository.ServeTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 功能：商品组 Service
 *
 * @author HuJianlin
 * @create 2018-03-15 14:35
 */
@Service("serveTypeService")
public class ServeTypeService extends DomainService {

    @Autowired
    ServeTypeRepository serveTypeRepository;

    public ServeType save(SimpleRequest request) {
        ServeType serveType = request.getO(ServeType.class);
        return serveTypeRepository.saveAndFlush(serveType);
    }

    /**
     * 删除
     * @param request
     * @return
     * @throws Exception
     */
    public String delete(SimpleRequest request) throws Exception  {
        checkData(request);
        ServeType serveType = request.getO(ServeType.class);
        serveTypeRepository.delete(serveType);
        return "删除成功";
    }
    public ServeType update(SimpleRequest request) {
        checkData(request);
        ServeType serveType = request.getO(ServeType.class);
        return serveTypeRepository.saveAndFlush(serveType);
    }
    /**
     * 检查数据判断，判读当前的输入版本信息
     * @param request
     */
    public void checkData(SimpleRequest request){
        String id = request.get("id");
        int version = request.get("version");

        // 从数据库中取数，检查数据
        ServeType serveType = serveTypeRepository.findOne(id);
        if (serveType == null) throw new RuntimeException("【" + id + "】在系统中不存在。");
        if (serveType.getVersion() != version) throw new RuntimeException("记录已更新或已删除，请重新提交！");
    }
}
